<template>
  <div class="ColdStorageDialog">
    <el-dialog title="冷藏信息维护" :visible.sync="$parent.DialogColdStorage" v-dialogDrag :modal-append-to-body="true"
               :modal="true" width="70%" @close="closeDialog()">
      <el-form :model="copyColdStorageInfo.coldStorage" :rules="rules" :inline="true" label-width="120px"
               ref="ColdStorage" :disabled="saveFlag">
        <el-row :gutter="5">
          <el-form-item label="遗体状态：">
            <span>{{ funeralDead.remainsState }}</span>
          </el-form-item>
          <el-form-item label="死亡原因：">
            <span>{{ funeralDead.deathCause }}</span>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="冷柜类型：" prop="equipmentTypeCode">
            <el-select v-model="copyColdStorageInfo.coldStorage.equipmentTypeCode"
                       @change="changeTypeCodeAsRuleItem(copyColdStorageInfo.coldStorage.equipmentTypeCode)"
                       :disabled="!ColdStorageAddFlag && (copyColdStorageInfo.coldStorage.charges.businessCharge.asSettled>0?true:false)"
                       placeholder="请选择" style="width: 120px;">
              <el-option
                v-for="(item,index) in ruleItems"
                :key="index"
                :label="item.dataText"
                :value="item.dataCode"
                :disabled="item.disableState>0?true:false"/>
            </el-select>
          </el-form-item>
          <el-form-item label="冷柜号：">
            <!-- <el-input v-model="equipmentselect.equipmentCode" :disabled="true">
              <span slot="append" style="cursor: pointer;" @click="select">查看</span>
            </el-input> -->
            <span>{{ copyColdStorageInfo.coldStorage.equipmentCode }}</span>
            <el-button type="primary" @click="select">查看</el-button>
          </el-form-item>
          <el-form-item label="冷藏状态：" prop="processStateCode">
            <el-select disabled v-model="copyColdStorageInfo.coldStorage.processStateCode" placeholder="请选择"
                       onkeydown="return (event.keyCode!=8)"
                       @change="changeProcessStateCode(copyColdStorageInfo.coldStorage.processStateCode)"
                       style="width: 120px;">
              <el-option
                v-for="(item,index) in  processStates"
                :key="index"
                :label="item.dataText"
                :value="item.dataCode"
                :disabled="item.disableState>0?true:false"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="入藏时间：" prop="appointmentInTime">
            <el-date-picker
              v-model="copyColdStorageInfo.coldStorage.appointmentInTime" format="yyyy-MM-dd HH:mm"
              type="datetime" @blur="loadChargeWithRule()"
              :disabled=" !ColdStorageAddFlag && (copyColdStorageInfo.coldStorage.charges.businessCharge.asSettled>0?true:false)"
              placeholder="选择日期时间" style="width: 100%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="出藏时间：">
            <el-date-picker
              v-model="copyColdStorageInfo.coldStorage.appointmentOutTime" format="yyyy-MM-dd HH:mm"
              type="datetime" @blur="loadChargeWithRule()"
              :disabled="!ColdStorageAddFlag &&(copyColdStorageInfo.coldStorage.charges.businessCharge.asSettled>0?true:false)"
              placeholder="选择日期时间" style="width: 100%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="冷藏费用：">
            <el-input v-model="copyColdStorageInfo.coldStorage.charges.businessCharge.itemCharge"
                      type="number"
                      :disabled="!ColdStorageAddFlag &&(copyColdStorageInfo.coldStorage.charges.businessCharge.asSettled>0?true:false)"
            ></el-input>
          </el-form-item>
          <!--协议村添加80-->
          <el-button type="primary" icon="el-icon-circle-plus-outline" circle
                     @click="loadChargeWithAgreementVillageAdd"></el-button>
          <!--协议村减少80-->
          <el-button type="success" icon="el-icon-remove-outline" circle
                     @click="loadChargeWithAgreementVillageSub"></el-button>
        </el-row>

        <el-row :gutter="5">
          <el-form-item label="规则描述：">
            <el-input type="textarea" v-model="copyColdStorageInfo.coldStorage.ruleRemark" :readonly="true"
                      style="width: 40vw"></el-input>
          </el-form-item>

        </el-row>

        <el-row :gutter="5">
          <el-form-item label="备注：">
            <el-input type="textarea" v-model="copyColdStorageInfo.coldStorage.remark" style="width: 40vw"></el-input>
          </el-form-item>
        </el-row>
        <div class="tablewrapper">
          <div class="table">
            <div class="title"><span>所有物品、服务</span>
              <!--<el-input v-model="search" placeholder="搜索物品/服务" style="width: 200px;float: right;"></el-input>-->
            </div>
            <el-table
              :data="copyGoodServices"
              :header-cell-style="{background:'rgb(246,247,251)',color:'#606266'}"
              border
              style="width: 99%;">
              <el-table-column align='center' prop="itemName" label="收费项目" sortable min-width="120"
                               column-key="serviceItemId">
              </el-table-column>
              <el-table-column
                prop="itemPrice"
                align='right'
                label="单价"
                min-width="80">
                <template slot-scope="{row,$index}">
                  <input class="edit-cell" type="number" v-if="row.asFixPrice !=1"
                         onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null"
                         v-model="row.itemPrice">
                  <label class="edit-cell" v-if="row.asFixPrice ==1">{{ row.itemPrice }}</label>
                </template>
              </el-table-column>
              <el-table-column
                prop="itemNumber"
                align='right'
                label="数量"
                min-width="50">
                <template slot-scope="{row,$index}">
                  <input class="edit-cell" type="number" v-model="row.itemNumber"
                         onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null">
                </template>
              </el-table-column>

              <el-table-column
                prop="itemUnit"
                align='center'
                label="单位"
                min-width="50">
              </el-table-column>
              <el-table-column
                prop="itemCharge"
                align='right'
                label="总金额"
                min-width="80">
                <template slot-scope="{row,$index}"
                          v-if="Number(row.itemPrice)>=0 &&Number(row.itemNumber)>=0&&Number(row.discountCharge)>=0">
                  {{
                    Number((row.itemPrice.match(/^\d+(?:.\d{0,2})?/)) * (row.itemNumber.match(/^\d+(?:.\d{0,2})?/))).toFixed(2)
                  }}
                </template>
              </el-table-column>
              <el-table-column
                prop="discountCharge"
                align='right'
                label="优惠"
                min-width="50">
                <template slot-scope="{row,$index}">
                  <input class="edit-cell" onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null"
                         v-model="row.discountCharge">
                </template>
              </el-table-column>
              <el-table-column
                label="物品剩余"
                align="center"
                prop="itemSurplusNum">
              </el-table-column>
              <el-table-column
                label="操作"
                align='center'
                min-width="100">
                <template slot-scope="{row,$index}">
                  <el-button
                    @click.native.prevent="AddRow($index,row)"
                    type="text"
                    size="small">
                    追加
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--<p class="tablecont">单价、数量、优惠三个字段值允许工作人员直接更改，更改完成后可通过“追加”按钮进行费用追加。</p>-->
          </div>
          <div class="table">
            <h3 class="title">已追加物品、服务</h3>
            <el-table
              :data="copyColdStorageInfo.coldStorage.charges.goodsServices"
              :header-cell-style="{background:'rgb(246,247,251)',color:'#606266'}"
              border
              style="width: 99%;">
              <el-table-column align='center' prop="itemName" label="收费项目" min-width="120">
              </el-table-column>
              <el-table-column
                prop="itemPrice"
                align='right'
                label="单价"
                min-width="80">
              </el-table-column>
              <el-table-column
                prop="itemNumber"
                align='right'
                label="数量"
                min-width="50">
              </el-table-column>
              <el-table-column
                prop="itemUnit"
                align='center'
                label="单位"
                min-width="50">
              </el-table-column>
              <el-table-column
                prop="itemCharge"
                align='right'
                label="项目金额"
                min-width="80">
              </el-table-column>
              <el-table-column
                prop="discountCharge"
                align='right'
                label="优惠"
                min-width="50">
              </el-table-column>
              <el-table-column
                prop="benefitCharge"
                align='right'
                label="减免"
                min-width="50">
              </el-table-column>
              <el-table-column
                prop="asSettled"
                align='center'
                label="结算状态"
                width="100">
                <template slot-scope="{row,$index}">
                  <span v-if="row.asSettled==0">未结算</span>
                  <span v-else-if="row.asSettled==1">已结算</span>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align='center'
                width="100">
                <template slot-scope="{row,$index}">
                  <el-button v-if="row.asSettled==0"
                             @click.native.prevent="deleteRow($index,copyColdStorageInfo.coldStorage.charges.goodsServices)"
                             type="text"
                             size="small">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--<p class="tablecont">此区域费用信息不允许更改，仅未结算的费用可以进行删除操作。-->
            <!--无论是新追加的费用还是删除的费用，均在保存操作后生效。-->
            <!--</p>-->
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: right">
        <el-button type="primary" @click="Save()" :disabled="saveFlag">保 存</el-button>
        <el-button type="primary" plain @click="$parent.DialogColdStorage = false">取 消</el-button>
      </div>

      <el-dialog
        title="冷柜号"
        :visible.sync="centerDialogVisible"
        width="70%"
        center>
        <div class="geweiwrapper" v-for="(item,m) in equipmentType" :style="{'margin-bottom':(m+1)%3==0 ?'50px':'0px'}"
             :key="m">
          <div class="box-card" v-for="(n,index) in item">
            <div class="item" :class="{sale:n.businessCode,free:n.flag==1?true:false,repair:n.flag==2?true:false}"
                 @click="selectequipment(item,index)">
              <h2 v-if="n.equipmentCode">{{ n.equipmentCode }}</h2>
              <h2 v-if="n.deadName">{{ n.deadName }}</h2>
              <h2 v-if="n.appointmentInTime">{{ n.appointmentInTime }}</h2>
            </div>
          </div>
        </div>

        <!-- <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveselecte">确 定</el-button>
        <el-button type="primary" plain @click="centerDialogVisible = false">取 消</el-button>
      </span>-->
      </el-dialog>

    </el-dialog>

  </div>
</template>

<script>
import * as Type from '@/api/service'
import {dataFormate} from '@/utils/index'
import {toFixed} from "@/utils/tofixed"

export default {
  name: "ColdStorageDialog",
  props: {
    DialogColdStorage: {
      type: Boolean,
      default: false
    },
    ColdStorageInfo: {
      type: Object,
      default: function () {
        return {
          coldStorage: {
            id: 0,
            businessCode: "",//业务编码
            equipmentTypeCode: "",//冷藏类型编码
            equipmentId: "",//冷藏设备外键
            equipmentCode: "",//冷藏设备编号
            appointmentInTime: "", //预约入藏时间
            appointmentOutTime: "",//预约出藏时间
            ruleNumber: 0,//规则数量
            ruleUnit: "",//规则单位
            ruleCode: "",//规则编码
            ruleRemark: "",//规则备注
            processStateCode: "",//流程状态
            version: 0,//版本
            remark: "",//备注
            calculateRule: "",//计算规则
            //业务费用与物品服务
            charges: {
              businessCharge: {
                id: 0,
                serviceItemId: 0,
                itemPrice: 0,
                itemNumber: 0,
                itemUnit: "string",
                itemCharge: 0,
                discountCharge: 0,
                benefitCharge: 0,
                realityCharge: 0,
                asSettled: 0,
                version: 0
              },
              goodsServices: [{
                id: 0,
                serviceItemId: 0,
                itemPrice: 1,
                itemNumber: 1,
                itemUnit: "m",
                itemCharge: 1,
                discountCharge: 0,
                benefitCharge: 0,
                realityCharge: 1,
                asSettled: 1,
                version: 0,
              }]
            }
          },
        }
      }
    },
    ColdStorageAddFlag: {    //true 为新增
      type: Boolean
    }, ProcessStateCodeOld: {//老状态
      type: Number
    },
    ruleItems: {
      type: Array
    },//冷藏流程状态
    processStates: {
      type: Array
    },
    funeralDead: {
      type: Object,
      default: function () {
        return {
          deathCause: "",//死亡原因
          remainsState: ""//遗体状态
        }
      }
    }//逝者信息
  },
  data() {
    return {
      //弹窗点击次数
      dialogHitNumber: 0,
      centerDialogVisible: false,
      saveFlag: false,     //保存过程中不可更改,true为正在保存

      rules: {
        equipmentTypeCode: [
          {required: true, message: '请选择类型', trigger: 'blur'},
        ],
        appointmentInTime: [
          {required: true, message: '请选择日期', trigger: 'blur'},
        ],
        appointmentOutTime: [
          {required: true, message: '请选择日期', trigger: 'blur'},
        ],
        processStateCode: [
          {required: true, message: '请选择流程状态', trigger: 'blur'}
        ],
        equipmentCode: [
          {required: true, message: '请选择冷柜', trigger: 'blur'}
        ],
      },

      formLabelWidth: '120px',

      /*//开始时间小于等于今天可选
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },*/
      dictionary: {},
      copyColdStorageInfo: this.ColdStorageInfo,
      coldStoragetime: "", //冷藏时间
      copyGoodServices: [],   //已追加服务物品
      equipmentType: {},       //冷藏柜数组
      equipmentselect: {},      //冷藏柜选中显示
      equipmentsave: {},             //冷藏柜选中显示中间值
      ruleItem: {},//收费规则
      onpresscTime: 0  //  阻止短时间内连续点击
    }
  },
  created() {
    this.$store.dispatch('user/getdictionary').then((res) => {     //获取字典数据
      this.dictionary = res;
      this.$set(this.dictionary, res)
    }).catch(() => console.log('promise catch err'))

  },
  watch: {
    '$parent.DialogColdStorage'() {
      this.copyColdStorageInfo = this.ColdStorageInfo
      this.copyGoodServices = JSON.parse(JSON.stringify(this.ColdStorageInfo.serviceItems.use_in_cold_storage))

      this.equipmentselect.equipmentCode = this.ColdStorageInfo.coldStorage.equipmentCode
      if (!this.ColdStorageAddFlag) {
        let appOutTimeWatch = this.copyColdStorageInfo.coldStorage.appointmentOutTime;
        let appInTimeWatch = this.copyColdStorageInfo.coldStorage.appointmentInTime;
        // let retTimeWatch=this.copyColdStorageInfo.coldStorage.returnTime;
        if (typeof appOutTimeWatch == "string" && appOutTimeWatch.indexOf("-") != -1) {
          this.copyColdStorageInfo.coldStorage.appointmentOutTime = appOutTimeWatch.replace(/-/g, "/");
        }
        if (typeof appInTimeWatch == "string" && appInTimeWatch.indexOf("-") != -1) {
          this.copyColdStorageInfo.coldStorage.appointmentInTime = appInTimeWatch.replace(/-/g, "/");
        }

      }
      this.$parent.DialogColdStorage = this.DialogColdStorage;
      if (this.$parent.DialogColdStorage == false) {
        this.ruleForm = {}
        this.$nextTick(() => {
          this.$refs.ColdStorage.resetFields();
        })
        this.equipmentselect.equipmentCode = ""
      }

      if (this.copyColdStorageInfo.coldStorage.equipmentTypeCode) {
        this.changeTypeCodeAsRuleItem(this.copyColdStorageInfo.coldStorage.equipmentTypeCode);
      }
      if (this.dialogHitNumber === 0) {
        this.dialogHitNumber++;
      } else {
        this.dialogHitNumber = 0;
      }
    }
  },
  computed: {
    /**
     * 计算两个日期相差的天数
     * sDate1和sDate2是2006-12-18格式
     */
    DateDiff() {
      var startDate = new Date(this.copyColdStorageInfo.coldStorage.appointmentInTime)
      var endDate = new Date(this.copyColdStorageInfo.coldStorage.appointmentOutTime);
      var ystart = startDate.getFullYear();
      var mstart = startDate.getMonth() + 1;
      var dstart = startDate.getDate();
      var start = Date.parse(ystart + "/" + mstart + "/" + dstart);   //.replace("-", "/").replace("-", "/")
      var yend = endDate.getFullYear();
      var mend = endDate.getMonth() + 1;
      var dend = endDate.getDate();
      var end = Date.parse(yend + "/" + mend + "/" + dend);
      if (startDate != "" || endDate != "") {
        if (startDate != "" && endDate != "" && start <= end) {
          var sjc = end - start;    //时间差的毫秒数
          var days = Math.floor(sjc / (24 * 3600 * 1000)) + 1;  //计算出相差天数
          return days;
        } else {
          alert("请输入正确的时间范围");
          return 0;
        }
      }
    },
  },
  methods: {
    //判断并选择费用
    changeTypeCodeAsRuleItem(code) {
      console.log(code, "code判断并选择费用");
      if (!code) {
        this.$message('code值无效')
        return;
      }
      this.equipmentselect.equipmentCode = ''
      //判断并选择费用
      if (this.ruleItems) {
        for (let i = 0; i < this.ruleItems.length; i++) {
          let item = this.ruleItems[i];
          //选中code'
          if (item.dataCode == code) {
            //服务项目id
            this.copyColdStorageInfo.coldStorage.charges.businessCharge.serviceItemId = item.serviceItemId;
            //服务项目价格
            this.copyColdStorageInfo.coldStorage.charges.businessCharge.itemPrice = item.itemPrice;

            //规则编码
            this.copyColdStorageInfo.coldStorage.ruleCode = item.ruleCode;
            //规则数量
            this.copyColdStorageInfo.coldStorage.ruleNumber = item.itemNumber;
            //计量单位
            this.copyColdStorageInfo.coldStorage.ruleUnit = item.itemUnit;
            //规则描述
            this.copyColdStorageInfo.coldStorage.ruleRemark = item.ruleDescribe;

            // 计算规则编码
            this.ruleItem.ruleCode = item.ruleCode;
            // 计算规则单价
            this.ruleItem.itemPrice = item.itemPrice;
            // 计算规则参数
            this.ruleItem.ruleParams = item.ruleParams;
            // console.log(this.dialogHitNumber, "弹窗点击this.dialogHitNumber")
            if (this.dialogHitNumber !== 0) {
              this.loadChargeWithRule();
            }
            break;
          }
        }
      }
    }, changeProcessStateCode(code) {
      //临时出仓的只能选入仓，已出仓的不能再改成临时入仓，
      let outFlag = (this.ProcessStateCodeOld == 4 && code != 2)
      // 已出仓的不允许再修改
      let outNotEdit = this.ProcessStateCodeOld == 3
      let flag = (!this.ColdStorageAddFlag && ((this.ProcessStateCodeOld > code) && this.ProcessStateCodeOld != 4));
      if (flag || outNotEdit || outFlag) {
        this.copyColdStorageInfo.coldStorage.processStateCode = this.ProcessStateCodeOld;
        this.$message('流程不能回退')
        return;
      }
    },
    //追加冷藏费用减少80
    loadChargeWithAgreementVillageSub() {

      /*  console.log(this.copyColdStorageInfo.coldStorage.charges.businessCharge.itemCharge
          , "点击未减少80");
  */
      //追加冷藏费用减少80
      this.copyColdStorageInfo.coldStorage.charges.businessCharge.itemCharge -= 80;
      this.$forceUpdate();
      /* console.log(this.copyColdStorageInfo.coldStorage.charges.businessCharge.itemCharge
         , "点击减少80");*/

    },
    //追加冷藏费用增加80
    loadChargeWithAgreementVillageAdd() {
      /*
            console.log(this.copyColdStorageInfo.coldStorage.charges.businessCharge.itemCharge
              , "点击未加80");*/
      //TODO不知道为啥直接+=80会自动变成小数,故先-1再+1
      this.copyColdStorageInfo.coldStorage.charges.businessCharge.itemCharge -= 1;
      this.copyColdStorageInfo.coldStorage.charges.businessCharge.itemCharge += 1;
      //追加冷藏费用增加80
      this.copyColdStorageInfo.coldStorage.charges.businessCharge.itemCharge += 80;
      this.$forceUpdate();
      /*      console.log(this.copyColdStorageInfo.coldStorage.charges.businessCharge.itemCharge
              , "点击加80");*/

    },
    //计算业务费用调用
    loadChargeWithRule() {
      //this.$message(this.ruleItem.ruleParams);

      if (!this.ruleItem) {
        return;
      }

      let ruleData = JSON.parse(this.ruleItem.ruleParams);

      ruleData.itemPrice = this.ruleItem.itemPrice;

      ruleData.appointmentInTime = dataFormate(new Date(this.copyColdStorageInfo.coldStorage.appointmentInTime))
      ruleData.appointmentOutTime = dataFormate(new Date(this.copyColdStorageInfo.coldStorage.appointmentOutTime))

      // this.$message(ruleData.appointmentInTime);

      let postData = {
        "ruleCode": this.ruleItem.ruleCode,
        "ruleData": JSON.stringify(ruleData)
      }
      Type['loadChargeWithRule'](postData).then(response => {
        let result = response;
        console.log(result, "计算费用返回值");
        const {data} = result
        if (!data) {
          this.$message('费用计算信息出错.')
        }

        //费用
        this.copyColdStorageInfo.coldStorage.charges.businessCharge.itemCharge = data.itemCharge;
        //规则编码
        this.copyColdStorageInfo.coldStorage.ruleCode = data.ruleCode;
        //规则数量
        this.copyColdStorageInfo.coldStorage.ruleNumber = data.ruleNumber;
        //计量单位
        this.copyColdStorageInfo.coldStorage.ruleUnit = data.ruleUnit;
        //规则描述
        this.copyColdStorageInfo.coldStorage.ruleRemark = data.ruleRemark;
        this.$forceUpdate();

        //数据读取成功
      }).catch(error => {
        this.$message(error)
      })
    },
    //保存
    Save() {
      if ((Date.now() - this.onpresscTime) > 2000) {
        this.onpresscTime = Date.now()
        console.log(Date.now())
      } else {
        return
      }
      let appointmentInTime = this.copyColdStorageInfo.coldStorage.appointmentInTime  //入藏时间
      let processStateCode = typeof (this.copyColdStorageInfo.coldStorage.processStateCode) == "number" && (this.copyColdStorageInfo.coldStorage.processStateCode >= 0)  //冷藏状态

      let equipmentTypeCode = typeof (this.copyColdStorageInfo.coldStorage.equipmentTypeCode) == "number" && (this.copyColdStorageInfo.coldStorage.equipmentTypeCode >= 0) //冷柜类型
      //let equipmentCode = this.equipmentselect.equipmentCode  //冷柜号
      let validate = !appointmentInTime || !processStateCode || !equipmentTypeCode
      if (validate) {
        this.$message("信息未填写完整")
        return
      }
      let obj = JSON.parse(JSON.stringify(this.copyColdStorageInfo.coldStorage))
      obj.charges.goodsServices.forEach((item, index) => {
        //业务编码赋值
        item.businessCode = obj.businessCode
        if (item.asSettled == 1) {
          obj.charges.goodsServices.splice(index, 1)
        }
      })
      if (this.ColdStorageAddFlag) {
        obj.id = 0
        obj.equipmentTypeCode = this.copyColdStorageInfo.coldStorage.equipmentTypeCode
        obj.equipmentId = this.copyColdStorageInfo.coldStorage.equipmentId
        obj.processStateCode = this.copyColdStorageInfo.coldStorage.processStateCode
        obj.appointmentInTime = dataFormate(new Date(obj.appointmentInTime))
        obj.appointmentOutTime = dataFormate(new Date(obj.appointmentOutTime))
        obj.returnTime = dataFormate(new Date(obj.returnTime))
        obj.version = 0
        obj.charges.businessCharge.id = 0
        obj.charges.businessCharge.businessCode = 0
        obj.charges.businessCharge.discountCharge = 0
        obj.charges.businessCharge.benefitCharge = 0
        obj.charges.businessCharge.asSettled = 0
        obj.charges.businessCharge.chargeSettleId = 0
        obj.charges.businessCharge.randomCode = 0
        obj.charges.businessCharge.version = 0
        obj.charges.businessCharge.chargeTime = ""
        obj.charges.businessCharge.businessCode = obj.businessCode
        obj.charges.businessCharge.itemCharge = toFixed(this.copyColdStorageInfo.coldStorage.charges.businessCharge.itemCharge, 2)
        obj.charges.businessCharge.realityCharge = this.copyColdStorageInfo.coldStorage.charges.businessCharge.itemCharge

      }
      if (!this.ColdStorageAddFlag) {
        console.log(obj.appointmentOutTime);
        obj.appointmentOutTime = dataFormate(new Date(obj.appointmentOutTime));
        obj.appointmentInTime = dataFormate(new Date(obj.appointmentInTime));
      }
      /*优惠，减免两位小数*/
      if (obj.charges.goodsServices.length > 0) {
        obj.charges.goodsServices.forEach((item, index) => {
          item.itemPrice = toFixed(item.itemPrice, 2)
          item.itemNumber = toFixed(item.itemNumber, 2)
          item.discountCharge = toFixed(item.discountCharge, 2)
          item.itemCharge = toFixed(item.itemCharge, 2)
        })
      }
      // console.log(obj)
      let postData = obj
      this.saveFlag = true;
      Type['savecoldstorage'](postData).then(response => {
        let result = response;
        const {data} = result
        if (!data) {
          this.saveFlag = false;
          this.$message('数据保存失败')
          return
        }
        //数据读取成功
        this.ColdStorageInfo.coldStorage = data
        this.saveFlag = false;
        this.$message('保存数据成功')
        this.$parent.DialogColdStorage = false
      }).catch(error => {
        this.$message(error)
        this.saveFlag = false;
      })
    },

    //追加
    AddRow(index) {
      let row = this.copyGoodServices[index]
      if (index >= 0 && row) {
        row.itemPrice = Number(row.itemPrice).toFixed(2);
        row.itemNumber = Number(row.itemNumber).toFixed(2);
        row.itemCharge = Number((row.itemPrice * row.itemNumber)).toFixed(2);   //计算项目金额
        row.discountCharge = Number(row.discountCharge).toFixed(2);
        let numberValidate = Number(row.itemPrice) >= 0 && Number(row.itemNumber) >= 0 && Number(row.discountCharge) >= 0
        if (!numberValidate || !Number(row.itemCharge) || (Number(row.itemCharge) < Number(row.discountCharge))) {
          this.$message("数值错误，请重新填写")
          Object.assign(row, this.copyColdStorageInfo.serviceItems.use_in_cold_storage[index])
          return true
        }
        // 减免金额
        row.benefitCharge = 0;
        row.asSettled = 0;
        //子项目的serviceItemId=id;
        row.serviceItemId = row.id;
        //新增的id为0
        row.id = 0;

        let list = JSON.parse(JSON.stringify(this.copyGoodServices));
        this.copyColdStorageInfo.coldStorage.charges.goodsServices.push(list[index])
        Object.assign(row, this.copyColdStorageInfo.serviceItems.use_in_cold_storage[index])
      }
    },
    //删除行
    deleteRow(index, arry) {
      let this_delete = this;
      //定义要删除的数据
      let item = {
        "id": arry[index].id,
        "version": arry[index].version
      };
      //先添加删除，后再删除服务物品
      let deleteItems = this_delete.copyColdStorageInfo.coldStorage.charges.deleteIds || [];
      if (arry[index] && item.id != 0) {
        //放入删除数据中
        deleteItems.push(item);
        //放入要要删除的数组中
        this_delete.copyColdStorageInfo.coldStorage.charges.deleteIds = deleteItems;
      }

      //删除指定数据
      this_delete.copyColdStorageInfo.coldStorage.charges.goodsServices.splice(index, 1);
    },
    //显示冷藏柜选择对话框
    select() {
      if (!this.copyColdStorageInfo.coldStorage.equipmentTypeCode) {
        //this.$message("请先选择冷柜类型")
        //不选择冷柜类型，默认全部冷柜类型
        this.equipment(null);
        //显示格位选择
        this.centerDialogVisible = !this.centerDialogVisible
        return
      }
      //判断冷藏柜是否已禁用
      if (this.ruleItems && this.ruleItems.length > 0) {
        for (let i = 0; i < this.ruleItems.length; i++) {
          let item = this.ruleItems[i];
          if (item && item.dataCode == this.copyColdStorageInfo.coldStorage.equipmentTypeCode && item.disableState) {
            this.$message("冷藏柜类型已禁用")
            return
          }
        }
      }
      this.equipment(this.copyColdStorageInfo.coldStorage.equipmentTypeCode)

      let code = this.copyColdStorageInfo.coldStorage.processStateCode
      // if (code && !this.ColdStorageAddFlag) {   //通过编辑进去
      //
      //   if (this.dictionary.refrigerated_state[code].dataText.indexOf("未入藏") > -1) {
      //     this.centerDialogVisible = !this.centerDialogVisible
      //   } else {
      //     this.$message("不是'未入藏'状态不允许修改")
      //   }
      //
      // } else {
      this.centerDialogVisible = !this.centerDialogVisible
      // }

    },
    //根据冷柜类型加载冷藏柜
    equipment(id) {
      if (id) {
        this.loadcoldstorageequipmentwithtype(id)
      } else {
        //加载所有冷藏柜的信息
        //this.$message("参数无效")
        this.loadcoldstorageequipmentwithalltype()
      }
    },
    //根据冷柜类型加载冷藏柜
    loadcoldstorageequipmentwithtype(id) {
      let postData = {
        typeCode: id
      }
      Type['loadcoldstorageequipmentwithtype'](postData).then(response => {
        let data = response.data;
        if (!data) {
          this.$message('数据读取失败')
          return
        }
        let obj = {};
        data.forEach(item => {
          if (!obj["" + item.rowNo]) {
            obj["" + item.rowNo] = []
            obj["" + item.rowNo].push(item)
          } else {
            obj["" + item.rowNo].push(item)
          }
        })
        for (let n in obj) {
          var sorted = obj[n].sort(function (x, y) {
            return x.columnNo - y.colusssmnNo;
          });
          obj[n] = sorted
        }
        this.equipmentType = obj;
        for (let i in this.equipmentType) {
          for (let j = 0; j < this.equipmentType[i].length; j++) {
            this.equipmentType[i][j].flag = false
          }
        }
      }).catch(error => {
        this.$message(error)
      })
    }, //根据冷柜类型加载冷藏柜
    loadcoldstorageequipmentwithalltype() {

      Type['loadcoldstorageequipmentwithalltype']().then(response => {
        let data = response.data;
        if (!data) {
          this.$message('数据读取失败')
          return
        }
        let obj = {};
        data.forEach(item => {
          if (!obj["" + item.rowNo]) {
            obj["" + item.rowNo] = []
            obj["" + item.rowNo].push(item)
          } else {
            obj["" + item.rowNo].push(item)
          }
        })
        for (let n in obj) {
          var sorted = obj[n].sort(function (x, y) {
            return x.columnNo - y.colusssmnNo;
          });
          obj[n] = sorted
        }
        this.equipmentType = obj;
        for (let i in this.equipmentType) {
          for (let j = 0; j < this.equipmentType[i].length; j++) {
            this.equipmentType[i][j].flag = false
          }
        }
      }).catch(error => {
        this.$message(error)
      })
    },
    //选择冷藏柜
    selectequipment(item, param) {
      this.equipmentselect = {}
      if (item[param].businessCode) {
        this.$message("冷柜被占用,请选择其他")
        return
      }
      for (let i in this.equipmentType) {
        for (let j = 0; j < this.equipmentType[i].length; j++) {
          this.equipmentType[i][j].flag = false
        }
      }
      item[param].flag = !item[param].flag
      Object.assign(this.equipmentType, this.equipmentType);
      this.equipmentsave = item[param]
      // for (let i in this.equipmentType) {
      //     for (let j = 0; j < this.equipmentType[i].length; j++) {
      //         if ((this.equipmentType[i][j].columnNo == item[param].columnNo) && (this.equipmentType[i][j].rowNo == item[param].rowNo)) {
      //             this.$set(this.equipmentType[i], j, item[param])
      //             this.equipmentsave = item[param]
      //         }
      //     }
      // }
      // console.log(this.equipmentselect)
    },
    //选择的被显示再界面上
    saveselecte() {
      this.equipmentselect = this.equipmentsave
      if (this.equipmentselect.id) {
        //选择冷柜不会影响冷藏状态
        //this.copyColdStorageInfo.coldStorage.processStateCode = ""
        //如果冷藏柜没有选冷藏类型，则反选冷藏类型
        if (!this.copyColdStorageInfo.coldStorage.equipmentTypeCode) {
          let equipmentCode = this.equipmentsave.equipmentCode;
          let equipmentId = this.equipmentsave.id;
          //调用类型转换函数
          //反选选择冷藏类型
          this.copyColdStorageInfo.coldStorage.equipmentTypeCode = this.equipmentsave.equipmentTypeCode;
          //加载规则
          this.changeTypeCodeAsRuleItem(this.copyColdStorageInfo.coldStorage.equipmentTypeCode);
          //let equipType=this.equipmentType;
          //再选冷柜各位
          this.copyColdStorageInfo.coldStorage.equipmentId = equipmentId;
          //重新赋值冷柜号
          this.equipmentselect.equipmentCode = equipmentCode;
          this.centerDialogVisible = false
        } else {
          this.copyColdStorageInfo.coldStorage.equipmentId = this.equipmentselect.id
          this.centerDialogVisible = false
        }

      }
    },
    closeDialog() {
      this.$parent.DialogColdStorage = false
    },

  }
}
</script>

<style>

.ColdStorageDialog .el-dialog__title, .ColdStorageDialog .el-dialog__headerbtn .el-dialog__close {
  color: white;
}

.ColdStorageDialog .el-input, .ColdStorageDialog .el-select, .ColdStorageDialog .el-form-item__content {
  width: 180px;
}

.ColdStorageDialog .el-textarea__inner {
  width: 40vw;
  min-width: 640px;
}

.ColdStorageDialog .el-drawer.rtl {
  padding: 2em;
  box-sizing: border-box;
}

.ColdStorageDialog .el-radio {

  display: block;
}

.ColdStorageDialog .el-card__body {
  padding: 0px;
}

.ColdStorageDialog .el-card__header {
  text-align: center;
}

.ColdStorageDialog .el-dialog--center .el-dialog__body {
  overflow: auto;
}

.el-dialog__wrapper {
  z-index: 9999
}
</style>
<style scoped>
.item {
  font-size: 16px;
  font-weight: 400;
  height: 90px;
  line-height: 30px;
  text-align: center;
  padding: 0 1em;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);;
  border: 1px solid #e9e9e9;
}

/deep/ .el-checkbox__label {
  font-size: 16px;
  font-weight: 700;
  line-height: 30px;
  text-align: center;
  padding: 0 1em;
}

.item:hover {
  cursor: pointer;
}

.item:last-child {
  margin-bottom: 0px;
}

.item.sale {
  background-color: #FF6040;
}

.item.free {
  background: lightgreen;
}

.item.repair {
  background: yellow;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.geweiwrapper {
  display: flex;
  flex-wrap: nowrap;
  margin: 5px 0px;
  justify-content: space-between;
}

.box-card {
  flex: 0 0 200px;
  display: inline-block;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);;
  margin-bottom: 0px;
  margin-right: 30px;
}

</style>

